"""
作品相关API路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.database import get_db
from app import models, schemas

router = APIRouter()


@router.get("/works", response_model=List[schemas.WorkListResponse])
async def get_works(
    skip: int = Query(0, ge=0, description="跳过记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回记录数"),
    is_active: Optional[bool] = Query(None, description="是否启用"),
    db: Session = Depends(get_db)
):
    """
    获取作品列表（用于首页）
    
    - **skip**: 分页偏移量
    - **limit**: 每页数量
    - **is_active**: 是否只返回启用的作品
    """
    query = db.query(models.Work)
    
    if is_active is not None:
        query = query.filter(models.Work.is_active == is_active)
    else:
        query = query.filter(models.Work.is_active == True)
    
    works = query.order_by(models.Work.created_at.desc()).offset(skip).limit(limit).all()
    return works


@router.get("/works/{work_id}", response_model=schemas.WorkResponse)
async def get_work(work_id: int, db: Session = Depends(get_db)):
    """
    获取作品详情
    
    - **work_id**: 作品ID
    """
    work = db.query(models.Work).filter(models.Work.id == work_id).first()
    if not work:
        raise HTTPException(status_code=404, detail="作品不存在")
    
    if not work.is_active:
        raise HTTPException(status_code=404, detail="作品已下架")
    
    return work


@router.post("/works", response_model=schemas.WorkResponse)
async def create_work(work: schemas.WorkCreate, db: Session = Depends(get_db)):
    """
    创建新作品（管理员功能）
    
    - **title**: 作品标题
    - **subtitle**: 作品副标题
    - **cover_image**: 封面图片URL
    - **description**: 作品描述
    - **images**: 作品图片列表
    """
    # 创建作品
    db_work = models.Work(
        title=work.title,
        subtitle=work.subtitle,
        cover_image=work.cover_image,
        description=work.description
    )
    db.add(db_work)
    db.flush()  # 获取work.id
    
    # 创建作品图片
    for idx, image in enumerate(work.images):
        db_image = models.WorkImage(
            work_id=db_work.id,
            image_url=image.image_url,
            sort_order=image.sort_order or idx
        )
        db.add(db_image)
    
    db.commit()
    db.refresh(db_work)
    return db_work


@router.put("/works/{work_id}", response_model=schemas.WorkResponse)
async def update_work(
    work_id: int,
    work: schemas.WorkUpdate,
    db: Session = Depends(get_db)
):
    """
    更新作品信息（管理员功能）
    """
    db_work = db.query(models.Work).filter(models.Work.id == work_id).first()
    if not db_work:
        raise HTTPException(status_code=404, detail="作品不存在")
    
    # 更新字段
    update_data = work.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_work, field, value)
    
    db.commit()
    db.refresh(db_work)
    return db_work


@router.delete("/works/{work_id}")
async def delete_work(work_id: int, db: Session = Depends(get_db)):
    """
    删除作品（管理员功能，软删除）
    """
    db_work = db.query(models.Work).filter(models.Work.id == work_id).first()
    if not db_work:
        raise HTTPException(status_code=404, detail="作品不存在")
    
    db_work.is_active = False
    db.commit()
    return {"message": "作品已删除"}

